import { defineConfig, loadEnv } from 'vite';
import createVitePlugins from './vite/plugins';
import autoprefixer from 'autoprefixer';
import path from 'path';
import { fileURLToPath, URL } from 'node:url';

export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_ENV, VITE_BASE_ROUTER } = env;
  return {
    base: VITE_APP_ENV === 'production' ? VITE_BASE_ROUTER : VITE_BASE_ROUTER,
    plugins: createVitePlugins(env, command === 'build'),
    resolve: {
      alias: {
        '~': path.resolve(__dirname, './'), // 设置路径
        '@': path.resolve(__dirname, './src'), // 设置别名
        '@myprint/design': path.resolve(__dirname, './design/src')
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    // vite 相关配置
    server: {
      port: 80,
      host: true,
      open: true,
      proxy: {
        '/dev-api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, '')
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler'
        }
      },
      postcss: {
        plugins: [
          // 浏览器兼容性
          autoprefixer(),
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ]
      }
    }
  };
});
